#include <boost/algorithm/string.hpp>
#include "_8BitConverter.h"
#include "Base64Coder.h"
#include "QPCoder.h"
#include "../../utils/UnicodeConverter.h"

namespace ba = boost::algorithm;
using namespace kc_sf;

_8BitConverter::_8BitConverter()
: c_encoding (_8Bit),
  c_charset (ASCII)
{
}

_8BitConverter::_8BitConverter(EncodingType enc, const std::string &charset)
: c_encoding (enc),
  c_charset (charset)
{
}

bool _8BitConverter::decode (const std::string &input, UnicodeString &output) const
{
	return c_encoding == Base64 ? decodeBase64(input, output)
			: c_encoding == Qp ? decodeQP(input, output)
			: decodeNoEncoding(input, output);
}

bool _8BitConverter::decodeBase64 (const std::string &input, UnicodeString &output) const
{
	bool success = false;

    // usunięcie z body CRLF
	std::string text_copy = ba::erase_all_copy(input, "\r\n");

    // dekodowanie
    Base64Coder b64coder;
    std::string decoded;
    if (b64coder.decode(text_copy, decoded))
    {
        // przeksztalcenie do unikodu
    	success = decodeNoEncoding(decoded, output);
    }

	return success;
}

bool _8BitConverter::decodeQP (const std::string &input, UnicodeString &output) const
{
    // zmiana CRLF w spacje
	std::string text_copy = ba::replace_all_copy(input, "\r\n", " ");

    // wewnętrzna reprezentacja potrzebna tylko dla qouted-printable
    QPCoder coder;
    std::string decoded;
    coder.decode(input, decoded);

	// przeksztalcenie do unikodu
	return decodeNoEncoding(decoded, output);
}

bool _8BitConverter::decodeNoEncoding (const std::string &input, UnicodeString &output) const
{
	// przeksztalcenie do unikodu
	output = UnicodeString( input.c_str() );
//	UnicodeConverter uconv(c_charset);
//	if (!uconv.encode(input, output))
//		return false;

	return true;
}
